package com.yonyou.cyxdms.basedata.client.service.basedata;

import com.yonyou.cyx.framework.bean.dto.base.ClientInfoDTO;
import com.yonyou.cyx.framework.compent.redis.RedisClient;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.utils.common.CommonUtils;
import com.yonyou.cyx.function.utils.jsonserializer.JSONUtil;
import com.yonyou.cyxdms.basedata.client.constants.BaseDataCommonConstants;
import com.yonyou.cyxdms.basedata.client.domains.vo.PackageCacheVO;
import com.yonyou.cyxdms.basedata.client.feign.BaseDataCommonClient;
import com.yonyou.cyxdms.basedata.client.util.ConditionMapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.List;
import java.util.Map;

/**
 * 配置信息
 *
 * @author: renwd
 * @since: 2018/11/29
 * @version:1.0 Copyright: Copyright (c) 2018
 */

@Service
public class BaseCommonPackageServiceImpl implements BaseCommonPackageService {

    private final Logger logger = LoggerFactory.getLogger(BaseCommonPackageServiceImpl.class);

    @Autowired
    private BaseDataCommonClient baseDataCommonClient;

    @Autowired
    private RedisClient redisClient;

    /**
     * 根据配置id查询配置信息
     *
     * @param packageId
     * @return com.yonyou.cyxdms.basedata.client.domains.vo.PackageCacheVO
     * @author renwd
     * @since 2019/9/10
     */
    @Override
    public PackageCacheVO getValueByPackageId(String packageId) {
        ClientInfoDTO loginInfoDto = ApplicationContextHelper.getBeanByType(ClientInfoDTO.class);
        String messageFormat = MessageFormat.format(BaseDataCommonConstants.PACKAGE_CACHE_PACKAGEID, loginInfoDto.getAppId());
        Object packageData = redisClient.hget(messageFormat, packageId);
        if (null == packageData) {
            // 重新加载这个id值的数据
            Map<String, Object> stringObjectMap = ConditionMapUtils.conditionMap(loginInfoDto.getAppId(), null);
            stringObjectMap.put("packageId", packageId);
            loadValueIfNotExists(stringObjectMap, messageFormat);
            Object redisPackageData = redisClient.hget(messageFormat, packageId);
            if (null == redisPackageData) {
                return null;
            }
            return JSONUtil.jsonToObj(JSONUtil.objectToJson(redisPackageData), PackageCacheVO.class);
        } else {
            return JSONUtil.jsonToObj(JSONUtil.objectToJson(packageData), PackageCacheVO.class);
        }
    }

    /**
     * 查询数据
     *
     * @param queryByMap
     * @author renwd
     * @since 2018/11/30
     */
    private void loadValueIfNotExists(Map<String, Object> queryByMap, String messageFormat) {
        List<PackageCacheVO> packageDtoResponse = baseDataCommonClient.queryPackageBySql(queryByMap).getData();
        logger.info("feign查询Package信息:{}", packageDtoResponse);

        if (!CommonUtils.isNullOrEmpty(packageDtoResponse)) {
            packageDtoResponse.stream().forEach(packageCacheDto -> initOneValue(packageCacheDto, messageFormat));
        }
    }

    /**
     * 数据放置redis
     *
     * @param packageCache packageCache
     * @author renwd
     * @since 2018/11/30
     */
    private void initOneValue(PackageCacheVO packageCache, String key) {
        redisClient.hsetExpire(key, String.valueOf(packageCache.getPackageId()), JSONUtil.objectToJson(packageCache), BaseDataCommonConstants.EXPIRE_TIME_ONE_DAY);
    }

    /**
     * 查询租户下的经销商下的所有配置
     *
     * @return java.util.List<com.yonyou.cyxdms.basedata.client.domains.vo.PackageCacheVO>
     * @author renwd
     * @since 2019/9/10
     */
    @Override
    public List<PackageCacheVO> listAllPackage() {
        ClientInfoDTO loginInfoDto = ApplicationContextHelper.getBeanByType(ClientInfoDTO.class);
        String messageFormat = MessageFormat.format(BaseDataCommonConstants.PACKAGE_CACHE_PACKAGE_ALL, loginInfoDto.getAppId(), loginInfoDto.getOwnerCode());
        Object packageData = redisClient.get(messageFormat);
        if (null == packageData) {
            List<PackageCacheVO> packageDtoResponse = baseDataCommonClient.queryPackageBySql(ConditionMapUtils.conditionMap(loginInfoDto.getAppId(), loginInfoDto.getOwnerCode())).getData();
            logger.info("feign查询Package信息:{}", packageDtoResponse);

            if (!CommonUtils.isNullOrEmpty(packageDtoResponse)) {
                redisClient.set(messageFormat, JSONUtil.objectToJson(packageDtoResponse), BaseDataCommonConstants.EXPIRE_TIME_ONE_DAY);
            }

            Object redisPackageData = redisClient.get(messageFormat);
            if (null == redisPackageData) {
                return null;
            }
            return JSONUtil.jsonToList(JSONUtil.objectToJson(redisPackageData), PackageCacheVO.class);
        } else {
            return JSONUtil.jsonToList(JSONUtil.objectToJson(packageData), PackageCacheVO.class);
        }
    }

    /**
     * 获取所有配置
     *
     * @param:
     * @return:
     * @auther: tanjie
     * @since: 2019/11/4
     */
    @Override
    public List<PackageCacheVO> getAllPackageByAppId(String appId) {
        String messageFormat = MessageFormat.format(BaseDataCommonConstants.PACKAGE_CACHE_PACKAGE_APPID_ALL, appId);
        //ClientInfoDTO loginInfoDto = ApplicationContextHelper.getBeanByType(ClientInfoDTO.class);
        Object packageDto = redisClient.get(messageFormat);
        if (null == packageDto) {
            // 查询所有数据
            List<PackageCacheVO> packageCacheVOS = baseDataCommonClient.getAllPackageByAppId(appId).getData();
            logger.info("feign查询series信息:{}", packageCacheVOS);
            if (!CommonUtils.isNullOrEmpty(packageCacheVOS)) {
                redisClient.set(messageFormat, JSONUtil.objectToJson(packageCacheVOS),
                        BaseDataCommonConstants.EXPIRE_TIME_ONE_DAY);
            }
            Object redisModelDto = redisClient.get(messageFormat);
            if (null == redisModelDto) {
                return null;
            }
            return JSONUtil.jsonToList(JSONUtil.objectToJson(redisModelDto), PackageCacheVO.class);
        } else {
            return JSONUtil.jsonToList(JSONUtil.objectToJson(packageDto), PackageCacheVO.class);
        }
    }

}
